<template>
  <PageLayout class="form-container">
    <a-card>
      <div class="form-title">
        {{ route.query.id ? "编辑" : "新增" }}升级任务
      </div>
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        layout="Vertical"
        :labelCol="{ style: { width: '120px' } }"
        :wrapperCol="{ style: { width: '120px' } }"
      >
        <a-form-item
          label="升级批次名称"
          name="name"
          required
          :wrapperCol="{ style: { width: '200px' } }"
        >
          <a-input
            style="width: 200px"
            v-model:value="formState.name"
            placeholder="请输入升级批次名称"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item
          label="升级设备列表"
          :colon="false"
          name="dataSource"
          required
        >
          <a-button type="primary" @click="add()">添加</a-button>
        </a-form-item>
        <!-- <BasicTable
          ref="tableRef"
          :columns="columns"
          :query-params="queryData"
          :apiFetch="postUserPage"
        >
          <template #bodyCell="{ column, record }"> </template>
        </BasicTable> -->

        <a-table
          :row-key="
            (record, index) => {
              return record.id || index;
            }
          "
          :pagination="pageOptions1"
          :columns="columns"
          :data-source="formState.dataSource"
          :scroll="{ x: 'calc(100%)' }"
        >
          <template #bodyCell="{ column, text }"> </template>
        </a-table>

        <div style="margin-bottom: 24px"></div>
        <a-form-item
          :labelCol="{ style: { width: '120px' } }"
          :wrapperCol="{ style: { width: '200px' } }"
          label="升级时间"
          name="installType"
          required
        >
          <a-select
            v-model:value="formState.installType"
            style="width: 200px; flex: none"
            placeholder="请选择"
            :options="[
              {
                label: '立即升级',
                value: '0',
              },
              {
                label: '选择升级时间',
                value: '1',
              },
            ]"
          ></a-select>
        </a-form-item>
        <a-form-item
          v-if="formState.installType == 1"
          :labelCol="{ style: { width: '120px' } }"
          :wrapperCol="{ style: { width: '200px' } }"
          label=" "
          :colon="false"
          name="installTime"
          required
        >
          <div style="width: 200px">
            <!-- <a-time-picker
              style="width: 200px"
              v-model:value="formState.installTime"
              value-format="HH:mm:ss"
            /> -->
            <a-date-picker
              show-time
                   style="width: 200px"
              v-model:value="formState.installTime"
              placeholder="Select Time"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="onChange"
              @ok="onOk"
            />
          </div>
        </a-form-item>

        <a-button
          type="primary"
          class="float-right"
          style="width: 100px"
          @click="save"
          >确定</a-button
        >
      </a-form>
    </a-card>

    <a-modal :width="800" v-model:visible="deviceVisible" @ok="comfirm">
      <div style="margin-top: 20px">
        <!-- :apiFetch="postFirmwareTaskDevicePage" -->
        <!-- <BasicTable
          ref="tableRef"
          :columns="columns1"
          :dataSource="dataSource"
          needSelect
        >
          <template #bodyCell="{ column, record }"> </template>
        </BasicTable> -->

        <a-table
          :row-key="
            (record, index) => {
              return record.id || index;
            }
          "
          @change="tableChange1"
          :pagination="pageOptions2"
          :row-selection="rowSelection"
          :columns="columns1"
          :data-source="dataSource1"
          :scroll="{ x: 'calc(100%)' }"
        >
          <template #bodyCell="{ column, text }"> </template>
        </a-table>
      </div>
    </a-modal>
  </PageLayout>
</template>

<script setup>
import {
  postFirmwareTaskAdd,
  postBannerUpdate,
  postBannerDetail,
  postFirmwareTaskDevicePage,
  postDevicePage,
} from "@/api/common";
import { useStoreCommonEnum } from "@/store";
import { message } from "ant-design-vue";
import { onMounted } from "vue";
const storeCommonEnum = useStoreCommonEnum();

const route = useRoute();
const router = useRouter();
const formRef = ref(null);

const formState = reactive({
  id: "",
  type: route.query.type,
  name: "",
  deviceIds: [],
  dataSource: [],
  firmwareId: route.query.id,
  installType: undefined,
  installTime: "",
});
const deptOptions = ref([]);

const columns = [
  {
    title: "序号",
    dataIndex: "index",
    width: "80px",
    customRender: (record) => `${record.index + 1}`,
  },

  {
    title: "设备编码",
    dataIndex: "deviceNo",
    key: "deviceNo",
    width: "200px",
    ellipsis: true,
  },
  {
    title: "设备机器号",
    dataIndex: "deviceSn",
    key: "deviceSn",
    width: "200px",
    ellipsis: true,
  },
  {
    title: "所属门店",
    dataIndex: "shopName",
    key: "shopName",
    width: "200px",
    ellipsis: true,
  },
  {
    title: "主控板版本",
    dataIndex: "mfw",
    key: "mfw",
    width: "200px",
    ellipsis: true,
  },
  {
    title: "WiFi模块版本",
    dataIndex: "gfw",
    key: "gfw",
    width: "200px",
    ellipsis: true,
  },

  {
    title: "操作",
    fixed: "right",
    dataIndex: "action",
    key: "action",
    width: 200,
  },
];

const columns1 = columns.filter((item) => {
  return item.key != "action";
});

onMounted(async () => {
  if (route.query.id) {
    postBannerDetail({ id: route.query.id }).then((res) => {
      for (let key in formState) {
        formState[key] = res.data[key];
      }
    });
  }
});

const rules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  imageUrl: [{ required: true, message: "请上传广告图" }],
  linkUrl: [{ required: true, message: "请输入链接", trigger: "blur" }],
  // deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
};

const save = () => {
  console.log("formState", formState);
  formRef.value.validate().then(() => {
    const requestUrl = formState.id ? postBannerUpdate : postFirmwareTaskAdd;
    const params = Object.assign({}, formState);
    delete params.dataSource;
    console.log("formState--", formState);
    requestUrl({ ...params }).then(() => {
      message.success(formState.id ? "编辑成功" : "新增成功");
      router.go(-1);
    });
  });
};
const pageOptions1 = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  size: "small",
  pageSizeOptions: ["10", "20", "30", "40", "50"],
  showQuickJumper: true,
  showSizeChanger: true, // 显示可改变每页数量
  showTotal: (total) => `共 ${total} 条`, // 显示总数,
  onChange: (current, pageSize) => {
    pageOptions1.value.current = current;
    pageOptions1.value.pageSize = pageSize;
  },
  onShowSizeChange: (current, pageSize) => {
    pageOptions1.value.current = current;
    pageOptions1.value.pageSize = pageSize;
  },
});
const pageOptions2 = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  size: "small",
  pageSizeOptions: ["10", "20", "30", "40", "50"],
  showQuickJumper: true,
  showSizeChanger: true, // 显示可改变每页数量
  showTotal: (total) => `共 ${total} 条`, // 显示总数,
  onChange: (current, pageSize) => {
    pageOptions2.value.current = current;
    pageOptions2.value.pageSize = pageSize;
  },
  onShowSizeChange: (current, pageSize) => {
    pageOptions2.value.current = current;
    pageOptions2.value.pageSize = pageSize;
  },
});

const tableChange1 = (...args) => {
  getPage1();
  // emit('change', ...args);
};
const tableChange2 = (...args) => {
  getPage2();
  // emit('change', ...args);
};

const dataSource = ref(
  Array.from({ length: 11 }, (item, index) => ({
    index,
    id: index,
    spaceName: "2121",
  }))
);
const dataSource1 = ref(
  Array.from({ length: 11 }, (item, index) => ({
    index,
    id: index,
    spaceName: "2121",
  }))
);

const deviceVisible = ref(false);
const add = () => {
  deviceVisible.value = true;
  // rowSelection.value.selectedRows = formState.dataSource.map((item) => item);
  // rowSelection.value.selectedRowKeys = formState.dataSource.map(
  //   (item) => item.id
  // );

  // currentSelectRows.value = formState.dataSource.map((item) => item);
  getPage1();
};

const getPage1 = async () => {
  let pageParams = {};
  pageParams["current"] = pageOptions2.value.current;
  pageParams["size"] = pageOptions2.value.pageSize;

  let params = {
    ...pageParams,
    firmwareInstallTaskId: route.query.id,
  };
  // 请求之前对数据操作
  const res = await postDevicePage(params);
  console.log("res", res);
  // resultData.value = res;
  // 判断返回值是否为数组
  dataSource1.value = res.data.records;
  pageOptions2.value.total = res.data.total;
};
const getPage2 = async () => {
  let pageParams = {};
  pageParams["current"] = pageOptions1.value.current;
  pageParams["size"] = pageOptions1.value.pageSize;

  let params = {
    ...pageParams,
    firmwareInstallTaskId: route.query.id,
  };
  // 请求之前对数据操作
  const res = await postDevicePage(params);
  console.log("res", res);
  // resultData.value = res;
  // 判断返回值是否为数组
  dataSource1.value = res.data.records;
  pageOptions1.value.total = res.data.total;
};

const comfirm = () => {
  console.log("dataSource.value----", dataSource.value);
  console.log("formState.deviceIds----", formState.deviceIds);
  formState.dataSource = currentSelectRows.value.map((item) => item);

  formState.deviceIds = formState.dataSource.map((item) => item.id);
  deviceVisible.value = false;
};
const currentSelectRows = ref([]);
const rowSelection = ref({
  selectedRowKeys: [],
  // selectedRows: [],
  // onSelect(record, selected, selectedRows, nativeEvent) {
  //   console.log({
  //     record,
  //     selected,
  //     selectedRows,
  //     nativeEvent,
  //   });
  // },
  // onSelectAll(selected, selectedRows, changeRows) {
  //   console.log({
  //     selected,
  //     selectedRows,
  //     changeRows,
  //   });
  // },
  // selectedRowKeys: {
  //   onSelect(changeableRowKeys) {
  //     console.log("changeableRowKeys--", changeableRowKeys);
  //   },
  // },
  onSelect(record, selected, selectedRows, nativeEvent) {
    console.log("用户手动选择/取消选择某列的回调---");
    console.log({
      record,
      selected,
      selectedRows,
      nativeEvent,
    });
    let keys = selectedRows.filter((item) => item).map((item) => item.id);
    let currentSlectKeys = currentSelectRows.value.map((item) => item.id);
    if (currentSelectRows.value.some((item) => record.id == item.id)) {
      currentSelectRows.value = currentSelectRows.value.filter((item) => {
        return item.id != record.id;
      });
    } else {
      currentSelectRows.value.push(record);
    }

    // formState.dataSource = currentSelectRows.value.map(item => item)
    rowSelection.value.selectedRowKeys = currentSelectRows.value.map(
      (item) => item.id
    );
    console.log("用户手动选择/取消选择某列的回调---");
  },
  onSelectAll(selected, selectedRows, changeRows) {
    console.log("用户手动选择/取消选择所有列的回调---");
    console.log({
      selected,
      selectedRows,
      changeRows,
    });
    let keys = changeRows.map((item) => item.id);
    let currentSlectKeys = currentSelectRows.value.map((item) => item.id);
    if (selected) {
      currentSelectRows.value = [
        ...new Map(
          [...currentSelectRows.value, ...changeRows].map((item) => [
            item.id,
            item,
          ])
        ).values(),
      ];
    } else {
      currentSelectRows.value = currentSelectRows.value.filter((item) => {
        return !keys.includes(item.id);
      });
    }
    // formState.dataSource = currentSelectRows.value.map(item => item)
    rowSelection.value.selectedRowKeys = currentSelectRows.value.map(
      (item) => item.id
    );
    console.log("用户手动选择/取消选择所有列的回调---");

    // let removeKeys = selectedRowKeys.filter((key) => {
    //   return currentSelectRows.value.some((ele) => ele.id == key);
    // });
    // let saveKeys = selectedRowKeys.filter((key) => {
    //   return !removeKeys.includes(key);
    // });
    // currentSelectRows.value = currentSelectRows.value.filter(
    //   (item) => !removeKeys.includes(item.id)
    // );
    // const saveRows = selectedRows.filter((ele) => saveKeys.includes(ele.id));
    // currentSelectRows.value = [...currentSelectRows.value, ...saveRows];

    // rowSelection.value.selectedRowKeys = currentSelectRows.value.map(
    //   (item) => item.id
    // );
  },

  onChange: (selectedRowKeys, selectedRows) => {
    console.log(
      `selectedRowKeys: ${selectedRowKeys}`,
      "selectedRows: ",
      selectedRows
    );
    console.log("selectedRowKeys--", selectedRowKeys);
    console.log(
      "rowSelection.value.selectedRows ",
      rowSelection.value.selectedRows
    );
    // let keys = selectedRowKeys;

    console.log("currentSelectRows.value", currentSelectRows.value);

    // 获取当前取消选中的行项
    // const unselectedKeys = rowSelection.value.selectedRowKeys.filter(
    //   (key) => selectedRowKeys.includes(key)
    // );

    // // 过滤掉被取消选中的行项
    // rowSelection.value.selectedRows = rowSelection.value.selectedRows.filter(
    //   (item) => !unselectedKeys.includes(item.id)
    // );

    // rowSelection.value.selectedRows = [
    //   ...new Map(
    //     [
    //       ...rowSelection.value.selectedRows,
    //       ...(selectedRows || []).filter(
    //         (item) => !formState.deviceIds.includes(item.id)
    //       ),
    //     ].map((item) => [item.id, item])
    //   ).values(),
    // ];

    // // 更新选中的行键值
    // rowSelection.value.selectedRowKeys = rowSelection.value.selectedRows.map(
    //   (item) => item.id
    // );
  },
  getCheckboxProps: (record) => ({
    // disabled:
    //   formState.dataSource &&
    //   formState.dataSource.some((item) => item.id == record.id), // Column configuration not to be checked
    name: record.name,
  }),
});
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 24px;
  margin-left: 130px;
  :deep(.ant-btn) {
    margin-right: 16px;
  }
}
</style>
